package com.ceba.test.modules.usermanage.service;
import java.util.List;
import java.util.Map;

import com.ceba.base.web.service.IBaseService;
import com.ceba.cebautils.DateUtil;
import org.json.JSONObject;

import com.ceba.test.base.configs.CebaConfig;
import com.ceba.test.modules.usermanage.dao.UserDao;
import com.ceba.test.modules.usermanage.entity.UUser;
import com.ceba.test.modules.usermanage.entity.Udepartment;
import com.ceba.test.modules.usermanage.entity.Uprivilege;

import abc.ID;
import abc.Value;
import abc.data.DataRow;
import abc.data.DataTable;
import abc.data.Sql;
import abc.data.SqlSessionManager;
import abc.util.StringUtils;

public class UserService extends IBaseService {

	private UserDao userDao;

	public String getUserRoleByUserId(String userId){
		return userDao.getUserRoleByUserId(userId);
	}



	public DataTable getOrganizeUserListSerivce (Map<String,Object> dic) throws Exception{
	 return  userDao.getOrganizeUserList(dic);
	}

	public DataTable getUserList (Map<String,Object> params,String orderBy) throws Exception{
		 return  userDao.getUserList(params,orderBy);
	}
	public long queryUserCount(){
		 return  userDao.queryUserCount();
	}

	public DataTable getUserListBySou (String key,String orderBy) throws Exception{
		 return  userDao.getUserListBySou(key,orderBy);
		}

	public String getUser (Map<String,Object> dic) throws Exception{
		 return  userDao.getUser(dic);
	}

	public DataTable editOrganizeList(Map<String,Object> dic) throws Exception{
		 return  userDao.editOrganizeList(dic);
	}

	public  DataTable getOrganizeList(Map<String,Object> dic) throws Exception{
		return  userDao.getOrganizeList(dic);
	}


	public  DataTable editRole(Map<String,Object> dic) throws Exception{
		return  userDao.editRole(dic);
	}

	public  DataTable getRole() throws Exception{
		return  userDao.getRole();
	}



	public boolean addOrganize(Map<String,Object>  dic) throws Exception{
		    boolean succes  = false ;
		    String id = ID.getGuid();
		    String name = (String)dic.get("NAME");
	        String  fullname =(String)dic.get("FULL_NAME");
	        String remapk =(String) dic.get("REMARK");
	    	String pid=(String)dic.get("PID");
	    	Udepartment udepartment = new Udepartment(id,name,fullname,remapk,pid);
	    	if(StringUtils.isNullOrEmpty(pid)){
			   return false;
			}
	    	else {
				long c=userDao.maxSetp(pid);
				if(c>0){
					c=c+1;
				}
				else {
					c=Value.getLong((String)dic.get("STEP")+"001");
				}
				udepartment.setStemp(c);

			    succes = userDao.addOrganize(udepartment);
			}

	    return succes;
	}



	/**
	 * 编辑用户
	 * @return
	 */
	public  boolean editUser(JSONObject obj,String loginUserId) throws Exception{

		  	String id=obj.getString("ID");
			String action="update";
			if(StringUtils.isNullOrEmpty(id)){
				id=ID.getGuid();
				action="insert";
			}
			//创建用户对象
			UUser user = new UUser(id, obj.getString("NAME"), obj.getString("LOGIN_ID"), obj.getString("DEPARTMENT_ID"));
		   //获取当前时间
			user.setCreateTime(DateUtil.getNowTime(""));
			user.setCreateUser(loginUserId);
            String pws=obj.getString("PASSWORD");

			if(StringUtils.isNotNullAndEmpty(pws)){
				user.setPassword(CebaConfig.getEncode(pws));
			}

			user.setRemark(obj.getString("REMARK"));

			if(action.equals("insert")){
				if (!userDao.addUser(user)) {
				 return	false;
				}else {
					Uprivilege uprivilege = new Uprivilege(ID.getGuid(),id,obj.getString("ROLE_ID"),"1");
					if (!userDao.addUprivilege(uprivilege)) {
					    return false;
					}
			   }

			}else {
				if (!userDao.updateUser(user)) {
					return false;
				}
				else {
					String role_id = obj.getString("ROLE_ID");
					if(!userDao.updateUprivilege(role_id, id)){
					  return false;
					}
				}
			}

	    return true;

	}

    public boolean addUser(Map<String,Object> dic,String loginUserId,String id,String action) throws Exception{
        UUser user = new UUser(id, (String)dic.get("userName"), (String)dic.get("loginName"),"");
        return addUser(user,loginUserId,dic,action,id);
    }

    public boolean addAdDomainUser(Map<String,Object> dic,String loginUserId,String id,String action) throws Exception{
        UUser user = new UUser(id, (String)dic.get("userName"), (String)dic.get("loginName"), "");
        return addUser(user,loginUserId,dic,action,id);
    }

    public boolean getUserByLoginId(String loginUserId){
        return userDao.getUserByLoginId(loginUserId);
    }


    public boolean addUser(UUser user,String loginUserId,Map<String,Object> dic,String action,String id) throws Exception{
        //获取当前时间
        user.setCreateTime(DateUtil.getNowTime(""));
        user.setCreateUser(loginUserId);
        String pws=(String)dic.get("password");

        if(StringUtils.isNotNullAndEmpty(pws)){
            user.setPassword(CebaConfig.getEncode(pws));
        }
        if(CebaConfig.LOGIN_TYPE.equals("1")){
            String	password = CebaConfig.getEncode(user.getLoginId());
            user.setPassword(password);
        }

        user.setRemark((String)dic.get("remark"));

        if(action.equals("insert")){
            if(userDao.getUserQueryByNameAndId(user.getLoginId(),user.getId())){
                if (!userDao.addUser(user)) {
                    return	false;
                }else {
                    Uprivilege uprivilege = new Uprivilege(ID.getGuid(),id,(String)dic.get("roleId"),"1");
                    if (!userDao.addUprivilege(uprivilege)) {
                        return false;
                    }
                }
            }else{
                return false;
            }


        }else {
            if (!userDao.updateUser(user)) {
                return false;
            }
            else {
                String role_id = (String)dic.get("roleId");
                if(!userDao.updateUprivilege(role_id, id)){
                    return false;
                }
            }
        }
        return true;
    }

	public boolean getUserQueryByName(String loginId){
		return userDao.getUserQueryByName(loginId);
	}

	public boolean getUserQueryByNameAndId(String loginId,String id){
		return userDao.getUserQueryByNameAndId(loginId,id);
	}



	public boolean deleteUser(String ID) throws Exception{
		Boolean suc1=false;
		Boolean suc2=false;

		if(ID != null){
			suc1=userDao.deleteUser(ID);
			suc2=userDao.deleteUprivilege(ID);
		}

		if((suc1.equals(true)) && (suc2.equals(true))){
		  return true;
	  }else {
		return false;
	}
	}


	public  String getUserRole(String userId ) throws Exception{
		return getUserRole(userId);
	}
	/**
	 * 获取所有的用户
	 * @return
	 * @throws Exception
	 */
	public List<UUser> getUserIds() throws Exception{
		return userDao.getUserIds();
	}

	/**
	 * 获取未添加用户章的用户
	 * @return
	 * @throws Exception
	 */
	public List<UUser> getUserIdsNotInStamp() throws Exception{
		return userDao.getUserIdsNotInStamp();
	}

	public Map<String,Object> queryUserById(String userId){
		return userDao.queryUserById(userId);
	}


	public UserDao getUserDao() {
		return userDao;
	}

	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

	private void copyDrToUuser(DataRow dr,UUser user){
		JSONObject object = dr.toJSONObject();
		user.setId(dr.getString("ID"));
		user.setName(dr.getString("NAME"));
		user.setUserRole(object.has("ROLE")?object.getString("ROLE"):"");
		user.setPassword(object.has("PASSWORD")?object.getString("PASSWORD"):"");
		user.setLoginIndex(object.has("LOGIN_INDEX")?object.getString("LOGIN_INDEX"):"");
		user.setLoginIndexSignVer(object.has("LOGIN_INDEX_SIGNVER")?object.getString("LOGIN_INDEX_SIGNVER"):"");
		user.setLoingIndexSignOnly(object.has("LOGIN_INDEX_SIGNONLY")?object.getString("LOGIN_INDEX_SIGNONLY"):"");
		user.setDepartmentId(object.has("department_ID")?object.getString("department_ID"):"");
		user.setStep(object.has("Step")?object.getString("Step"):"");
	}
	/**
	 * 根据ID获取用户
	 */
	public UUser getUserById(String userId){
		UUser user = new UUser();
		DataTable dt = userDao.getUserById(userId);
		if(dt!=null && dt.getRowCount()>0){
			DataRow row = dt.getRow(0);
			copyDrToUuser(row,user);
		}
		return user;
	}
}
